package cn.gov.pbc.tims.util;
 /** 
 * 
 * @author geloin 
 * @date 2012-5-5 下午12:05:57 
 */  
 
  
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
/** 
 *  
 * @author geloin 
 * @date 2012-5-5 下午12:05:57 
 */  
public class FileOperateUtil {  
    private static final String REALNAME = "realName";  
    private static final String STORENAME = "storeName";  
    private static final String SIZE = "size";  
    private static final String SUFFIX = "suffix";  
    private static final String CONTENTTYPE = "contentType";  
    private static final String CREATETIME = "createTime";  
    private static final String UPLOADDIR = "uploadDir/";  
  
    /** 
     * 将上传的文件进行重命名 
     *  
 
     * @param name 
     * @return 
     */  
    private static String rename(String name) {  
  
        Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss")  
                .format(new Date()));  
        Long random = (long) (Math.random() * now);  
        String fileName = now + "" + random;  
  
        if (name.indexOf(".") != -1) {  
            fileName += name.substring(name.lastIndexOf("."));  
        }  
  
        return fileName;  
    }  
  
    /** 
     * 压缩后的文件名 
     *  
 
     * @param name 
     * @return 
     */  
    private static String zipName(String name) {  
        String prefix = "";  
        if (name.indexOf(".") != -1) {  
            prefix = name.substring(0, name.lastIndexOf("."));  
        } else {  
            prefix = name;  
        }  
        return prefix + ".zip";  
    }  
  /*
    *//** 
     * 上传文件 
     *  
 
     * @param request 
     * @param params 
     * @param values 
     * @return 
     * @throws Exception 
     *//*  
    public static List<Map<String, Object>> upload(HttpServletRequest request,  
            String[] params, Map<String, Object[]> values) throws Exception {  
  
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();  
  
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;  
        Map<String, MultipartFile> fileMap = mRequest.getFileMap();  
  
        String uploadDir = request.getSession().getServletContext()  
                .getRealPath("/")  
                + FileOperateUtil.UPLOADDIR;  
        File file = new File(uploadDir);  
  
        if (!file.exists()) {  
            file.mkdir();  
        }  
  
        String fileName = null;  
        int i = 0;  
        for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet()  
                .iterator(); it.hasNext(); i++) {  
  
            Map.Entry<String, MultipartFile> entry = it.next();  
            MultipartFile mFile = entry.getValue();  
  
            fileName = mFile.getOriginalFilename();  
  
            String storeName = rename(fileName);  
  
            String noZipName = uploadDir + storeName;  
            String zipName = zipName(noZipName);  
  
            // 上传成为压缩文件  
            ZipOutputStream outputStream = new ZipOutputStream(  
                    new BufferedOutputStream(new FileOutputStream(zipName)));  
            outputStream.putNextEntry(new ZipEntry(fileName));  
            outputStream.setEncoding("GBK");  
  
            FileCopyUtils.copy(mFile.getInputStream(), outputStream);  
  
            Map<String, Object> map = new HashMap<String, Object>();  
            // 固定参数值对  
            map.put(FileOperateUtil.REALNAME, zipName(fileName));  
            map.put(FileOperateUtil.STORENAME, zipName(storeName));  
            map.put(FileOperateUtil.SIZE, new File(zipName).length());  
            map.put(FileOperateUtil.SUFFIX, "zip");  
            map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream");  
            map.put(FileOperateUtil.CREATETIME, new Date());  
  
            // 自定义参数值对  
            for (String param : params) {  
                map.put(param, values.get(param)[i]);  
            }  
  
            result.add(map);  
        }  
        return result;  
    }  */
  
    /** 
     * 下载 
     *  
     * @date  下午12:25:39 
     * @param request 
     * @param response 
     * @param storeName 
     * @param contentType 
     * @param realName 
     * @throws Exception 
     */  
    public static void download(HttpServletRequest request,  
            HttpServletResponse response, String storeName, String contentType,  
            String realName) throws Exception {  
        request.setCharacterEncoding("UTF-8");  
        BufferedInputStream bis = null;  
        BufferedOutputStream bos = null;  
        String ctxPath = request.getSession().getServletContext()  
                .getRealPath("/")  
                + FileOperateUtil.UPLOADDIR;  
        String downLoadPath = ctxPath + storeName;  
        long fileLength = new File(downLoadPath).length();  
        response.setContentType(contentType);  
        response.setHeader("Content-disposition", "attachment; filename="  
                + new String(realName.getBytes("utf-8"), "ISO8859-1"));  
        //response.setHeader("Content-Length", String.valueOf(fileLength));  
  
        bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
        bos = new BufferedOutputStream(response.getOutputStream());  
        byte[] buff = new byte[2048];  
        int bytesRead;  
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
            bos.write(buff, 0, bytesRead);  
        }  
        bis.close();  
        bos.close();  
    }  
    
    //下载
    public static void download(HttpServletRequest request,  
            HttpServletResponse response,  String contentType,  
            String realName, InputStream iss) throws Exception {  
        request.setCharacterEncoding("UTF-8");  
        BufferedInputStream bis = null;  
        BufferedOutputStream bos = null;  
  
        //String ctxPath = request.getSession().getServletContext()  
        //        .getRealPath("/")  
        //        + FileOperateUtil.UPLOADDIR; 
        long fileLength=iss.available();
        response.setContentType(contentType);  
        response.setHeader("Content-disposition", "attachment; filename="  
                + new String(realName.getBytes("utf-8"), "ISO8859-1"));  
        response.setHeader("Content-Length", String.valueOf(fileLength));  
        bis = new BufferedInputStream(iss); 
        bos = new BufferedOutputStream(response.getOutputStream());  
        byte[] buff = new byte[1024];  
        int bytesRead;  
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
            bos.write(buff, 0, bytesRead);  
        }   
        bis.close();  
        bos.close();  
    }  
    public static void download(OutputStream outputStream,   
          InputStream iss,long fileLength) throws Exception {  
        BufferedInputStream bis = null;  
        BufferedOutputStream bos = null;  
        bis = new BufferedInputStream(iss); 
        bos = new BufferedOutputStream(outputStream);  
        byte[] buff = new byte[1024];  
        int bytesRead;  
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
            bos.write(buff, 0, bytesRead);  
        }   
        bis.close();  
        bos.close();  
    }  
    public static void saveFile(String fileName, String storeDir,InputStream in) throws Exception {

		String osName = System.getProperty("os.name");
		String separator = "";

		if (osName == null) {
			osName = "";
		}
		if (osName.toLowerCase().indexOf("win") != -1) {
			separator = "\\";
		} else {
			separator = "/";
		}

		File storeFile = new File(storeDir + separator + fileName);

		//System.out.println("附件的保存地址:　" + storeFile.toString());

		// for(int i=0;storefile.exists();i++){

		// storefile = new File(storedir+separator+fileName+i);

		// }
		BufferedOutputStream bos = null;

		BufferedInputStream bis = null;
		

		try {

			bos = new BufferedOutputStream(new FileOutputStream(storeFile));

			bis = new BufferedInputStream(in);
			System.out.println("size41="+in.available());
			int c;

			while ((c = bis.read()) != -1) {

				bos.write(c);

				bos.flush();

			}
			

		} catch (Exception exception) {

			exception.printStackTrace();

			throw new Exception("文件保存失败!");

		} finally {

			bos.close();

			bis.close();

		}

	}
   
    public static String readWord(InputStream ins,String suffix ) {
		String buffer = "";
		try {
			if (suffix.endsWith(".doc")) {
				WordExtractor ex = new WordExtractor(ins);
				buffer = ex.getText();
			} else if (suffix.endsWith(".docx")) {
				OPCPackage opcPackage = OPCPackage.open(ins);
				POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
				buffer = extractor.getText();
				extractor.close();
			} else if (suffix.endsWith(".wps")){
				WordExtractor ex = new WordExtractor(ins);
				buffer = ex.getText();
			}
 
		} catch (Exception e) {
			e.printStackTrace();
		}
 
		return buffer;
	}
    public static String readTxt(InputStream ins) {
    	String buffer = "";
    	try {
			BufferedReader br = new BufferedReader(new InputStreamReader(ins, "GBK"));// 构造一个BufferedReader类来读取文件
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
				buffer = buffer + "\n" + s;
		}
		br.close();
	  } catch (Exception e) {
		e.printStackTrace();
	  }
		return buffer;
	}
    public static String readPdf(InputStream ins) {
    	PDDocument document;
    	String buffer = "";
		try {
			document = PDDocument.load(ins);
			PDFTextStripper stripper=new PDFTextStripper();
			stripper.setSortByPosition(false);
			buffer=stripper.getText(document);
			document.close();
		} catch (InvalidPasswordException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return buffer;
	} 
 

}  